
<template>
  <div class="" style="height:100%">
        <div class="layout-container-detail">
           <el-form :model="formData" label-width="170px">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="团队功能：">
                                <el-switch 
                                :inline-prompt="true"
                                v-model="formData.ZXZ_TEAM_PROFILE_ALL" 
                                :before-change="(()=>{return handleOpt('ZXZ_TEAM_PROFILE_ALL')})"
                                />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="团队自主创建条件：">
                            <el-col :span="24" class="flex-start-nowrap">
                                历史芝草大于等于
                                <el-col :span="12">
                                    <el-input v-model="formData.ZXZ_TEAM_PROFILE_CREATE" placeholder="" />
                                </el-col> 
                                <el-button type="primary" @click="handleOpt('ZXZ_TEAM_PROFILE_CREATE')">修改</el-button>
                            </el-col>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" style="height:47px">
                            <el-form-item label="有效人数定义：" label-width="120px">
                                <div class="flex-start-nowrap">只属于该团队</div>
                                    <el-row >
                                            <el-col class="flex-start-nowrap" :span="18"> 完成实名认证 </el-col> 
                                            <el-col :span="5" class="flex-start-nowrap">
                                                <el-switch 
                                                :inline-prompt="true"
                                                :before-change="(()=>{return handleOpt('ZXZ_TEAM_PROFILE_AUTH_PEOPLE')})"
                                                v-model="formData.ZXZ_TEAM_PROFILE_AUTH_PEOPLE" 
                                                />
                                            </el-col>
                                    </el-row>
                                    <el-row>
                                            <el-col class="flex-start-nowrap" :span="8">历史芝草大于等于 </el-col> 
                                            <el-col :span="5">
                                                <el-input v-model="formData.ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME_number" placeholder="" />
                                            </el-col> 
                                            <el-col :span="5" class="flex-start-nowrap" :offset="0">
                                                <el-button type="primary"  @click="handleOpt('ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME_number')">修改</el-button>
                                            </el-col>
                                            
                                            <el-col :span="5" class="flex-start-nowrap" >
                                                <el-switch 
                                                :inline-prompt="true"
                                                :before-change="(()=>{return handleOpt('ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME')})"
                                                v-model="formData.ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME"  />
                                            </el-col>
                                    </el-row>
                            </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="团队创建活动：">
                                <el-switch 
                                :inline-prompt="true"
                                v-model="formData.ZXZ_TEAM_PROFILE_ACTIVITY" 
                                :before-change="(()=>{return handleOpt('ZXZ_TEAM_PROFILE_ACTIVITY')})"
                                />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                            <el-form-item label="团队创建消耗芝草：">
                            <div  class="flex-start-nowrap">
                                <el-col :span="18">
                                    <el-input v-model="formData.ZXZ_TEAM_PROFILE_CREATE_CONSUME" placeholder="" />
                                </el-col> 
                                <el-button type="primary"  @click="handleOpt('ZXZ_TEAM_PROFILE_CREATE_CONSUME')">修改</el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="团队创建活动开启时间：">
                            <el-col :span="24">
                                <el-col :span="20">
                                    <el-date-picker v-model="formData.ZXZ_TEAM_PROFILE_ACTIVITY_TIME" type="datetimerange" prefix-icon="el-icon-date"
                                    range-separator="→" value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期"
                                    style="width: 100%" />
                                </el-col>
                                <el-button type="primary" @click="handleOpt('ZXZ_TEAM_PROFILE_ACTIVITY_TIME')">修改</el-button>
                            </el-col>
                    </el-form-item>
                    </el-col>
                  
                  
                </el-row>
            </el-form>
        </div>
        <div class="layout-container">
                <div class="layout-container-opts" style="">
                     <div style="padding:0 20px 0 23px">
                        <el-checkbox v-model="checkAll" label="全选" @change="changeAll"></el-checkbox>
                    </div>
                    <el-button v-for="(item,index) in tabList.list" :key="index" 
                    :type="index == tabList.index ?'primary':'default'"
                    v-loading="exportAllLoading"
                     @click="clickBtn(item,index)">
                    {{item.text}}
                    </el-button>
                </div>
                <!-- <el-radio-group v-model="tabList.index" style="margin-bottom: 30px">
                    <el-radio-button v-for="(item,index) in tabList.list" :key="index" :label="item.label">{{item.text}}</el-radio-button>
                </el-radio-group> -->
            <div class="layout-container-table">
                <Table ref="table" v-model:page="page" :showSelection="true"
                    :data="tableData"
                    @getTableData="getTableData" @selection-change="handleSelectionChange">
                    <el-table-column 
                    v-for="(item,index) in columns" :type="item.type" :key="index"
                    :label="item.label"
                    :property="item.property">
                        <template #default="scope" v-if="item.input">
                            <el-input v-model="scope.row.dict_number" placeholder="" />
                        </template>
                         <template #default="scope" v-if="item.property == 'Id'">
                            <span>{{scope.row[item.property]}}</span>
                        </template>
                        <template  #default="scope" v-else>
                            <template v-if="item.property">
                                <el-input
                                    v-if="scope.row.showInput" 
                                    v-model="scope.row[item.property]" 
                                    placeholder="" />
                                <span v-else>{{scope.row[item.property]}}</span>
                            </template>
                        </template>
                       
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #default="scope">
                            <el-button type="text" v-if="!scope.row.showInput" @click="updateRow(scope.row,scope.$index)">修改</el-button>
                            <template v-else>
                                <el-button type="text" @click="updateRowSure(scope.row,scope.$index)">确认</el-button>
                                <el-button type="text" @click="updateRowCancel(scope.row,scope.$index)">取消</el-button>
                            </template>
                            
                        </template>
                    </el-table-column>
                </Table>
            </div>
        </div>
         <!-- 上传文件弹出框组件 -->
        <BatchImportDialog 
        v-if="uploadObj.visible"
        :visible="uploadObj.visible"
        :title="uploadObj.title"
        :uploadObj="uploadObj"
        @closeUploadDialog="closeUploadDialog"
        @refreshTable="refreshTable"/>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, ref, reactive,nextTick  } from "vue";
import { Page } from "@/components/table/type";
import { ElMessage, ElMessageBox } from "element-plus";
import Table from "@/components/table/index.vue";
import BatchImportDialog from "@/components/uploadFile/batchImportDialog.vue";
import {
 teamProfile,effectiveNumber,teamIncome,profileUpdate,effectiveNumberUpdate,incomeUpdate,incomeImport,incomeExport
} from "@/api/team.ts";
import { dateFormat, intervalTime, calculateDiffTime } from "@/utils/index.ts";
import { getTopicQuantity } from "@/api/service/user.ts";
import { useStore } from "vuex";
import { ossPrefix,ossPrefixNew } from "@/utils/index.ts";
// 存储搜索用的数据
const formData = reactive({
  ZXZ_TEAM_PROFILE_ACTIVITY_TIME:[],//array
});

// 分页参数, 供table使用
const page: Page = reactive({
  index: 1,
  size: 50,
  total: 0,
});
// 存储搜索用的数据
const columns = ref([])
const profileData = reactive({})
const columns1 = reactive([
    {
        label:'序号',
        property:'Id', 
    },
    {
        label:'项目ID',
        property:'project_id',
    },{
        label:'项目名称',
        property:'title',
    },{
        label:'提成形式（1表示基础工资，2表示固定值）',
        property:'income_type',
    },{
        label:'团队等级',
        property:'level',
    },{
        label:'提成',
        property:'income_number',
    },
]);
columns.value = columns1

// 存储搜索用的数据
const tableData = ref([
    {
        level:1,
        number:1
    },{
        level:2,
        number:1
    },{
        level:3,
        number:1
    },
]);
// 存储搜索用的数据
const tabList = reactive({
    index:0,
    list:[
        // {
        //     label:'0',
        //     text:'团队各等级要求有效人数',
        //     func:'test',
        // },{
        //     label:'1',
        //     text:'团队收益设置',
        //      func:'test',
        // },
        {
            label:'0',
            text:'上传表格创建/修改团队收入',
             func:'test',
        },{
            label:'1',
            text:'导出团队收入设置表',
             func:'export',
        },
    ]
});
const clickBtn = (item:any,index:any)=>{
     if(index == 0){
        handleBatchImport()
    }else if(index == 1){
        exportProjectAnalysisFun()
    }
}
// 操作
const handleOpt = (type:String) => {
    return new Promise<void>((resolve, reject) => {
            ElMessageBox.confirm(`是否确认当前操作?`, "", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "success",
        }).then(()=> {
            
            let boolean =(typeof(formData[type]) == 'boolean') 
            let object =(typeof(formData[type]) == 'object') 
            let string =(typeof(formData[type]) == 'string') 
            let val:any = ''
            // ?formData[type]?1:0;
            let par = {
                id:profileData[type],
            }
            if(boolean){
                par.number = formData[type]?0:1;
            }
            if(object){
                //  par.val = formData[type]
                 par.val = formData[type][0] || ''
                 par.description = formData[type][1] || ''

            }
            if(string){
                 par.val = formData[type]
            }
            if(par.hasOwnProperty('val')){
                par.val += ''
            }
           
            if(type == 'ZXZ_TEAM_PROFILE_CREATE' || type =='ZXZ_TEAM_PROFILE_CREATE_CONSUME'){
                par.number =  par.val * 1
                delete par.val
            }
            if(type == 'ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME'){
                par.val = formData.ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME_number
            }
             if(type == 'ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME_number'){
                 par.number = formData['ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME']?1:0;
             }
            profileUpdate(par).then(res => {
                if(res.code == 200){
                    ElMessage.success('操作成功！');
                    resolve(true)
                }else{
                     reject() 
                }
            })
           
        }).catch(()=>{
            reject() 
        })
    })
 
}
// 批量导入用户
const uploadObj = reactive({
  fileType: ['.xls', '.xlsx'],
  accept: '.xls, .xlsx', // 文件上传类型
  multiple: false, // 是否支持多选
  visible: false,
  title: '',
  url: '', // 批量导入用户接口地址
  type:'team',
  downloadObj: {
    name: '',
    url: ''
  }
});
const closeUploadDialog = ()=>{
    uploadObj.visible = false
}
const refreshTable = ()=>{
    debugger
    ElMessage.success("导入成功！")
    closeUploadDialog()
    getTableData(true)
}

const handleBatchImport = () => {
  uploadObj.visible = true;
  uploadObj.title = '批量导入团队收益设置';
  uploadObj.url = '/admin/team/income_import';
  uploadObj.downloadObj.name = '团队收益设置表.xlsx'; // excel模板名称
  uploadObj.downloadObj.url = `${ossPrefixNew}团队收益设置表.xlsx`; // excel模板下载地址
}

const table = ref()
const checkAll = ref(false)
const changeAll = (e:any)=>{
    console.log(checkAll.value)
    if(e){
        if(selectData.value.length == tableData.value.length) return
        table.value.$refs.systemTable.toggleAllSelection()
    }else{
        selectData.value = [];
        table.value.$refs.systemTable.clearSelection()
    }
}
// 勾选数据
const selectData = ref([]); // 系统id
const handleSelectionChange = (data: any) => {
  selectData.value = [];
  if(data.length){
    if(data.length != tableData.value.length){
      checkAll.value = false
    }
    data.forEach((item: any) => {
      selectData.value.push(item.Id);
    });
  }
};



const getTableData = (init:Boolean)=>{
   if(init) page.index = 1
   getTeamIncome()
}
const getTeamIncome =()=>{
     teamIncome({page:page.index,page_size:page.size}).then(res=> {
        if(res.code == 200){
            tableData.value = res.data.list
            if(checkAll.value){
                changeAll(true)
            }else{
        changeAll(false)
      }
            page.total = Number(res.data.count);
        }
        
     })
}
const updateRow =(row:any,index:any)=>{
    tableData.value.splice(index,1,{...row,showInput:true})
    
}
const updateRowCancel = (row:any,index:any)=>{
    tableData.value.splice(index,1,{...row,showInput:false})
    
}
const updateRowSure = (row:any,index:any)=>{
    console.log(tableData.value[index])
    
    let par = {
        "Id":row.Id,
        "project_id":row.project_id,
        "title":row.title ,
        "income_type":row.income_type* 1,
        "level":row.level * 1,
        "income_number":row.income_number * 1,
    }
     incomeUpdate(par).then((res:any) => {
        if(res.code == 200){
            tableData.value.splice(index,1,{...row,showInput:false})
            ElMessage.success("修改成功！")
        }else{
            ElMessage.success("修改失败！")
        }
        
     })
}
getTeamIncome()
const getProfile =()=>{
    teamProfile().then(res=> {
        if(res.code == 200){
            res.data.map(item => {
                profileData[item.dict_code] = item.Id
                if(item.dict_code == 'ZXZ_TEAM_PROFILE_ALL'){
                    formData[item.dict_code] = item.dict_number == 1?true:false
                }
                if(item.dict_code == 'ZXZ_TEAM_PROFILE_ACTIVITY'){
                    formData[item.dict_code] = item.dict_number == 1?true:false
                }
                if(item.dict_code == 'ZXZ_TEAM_PROFILE_ACTIVITY_TIME'){
                    formData[item.dict_code] = [item.dict_value,item.avatar]
                }
                if(item.dict_code == 'ZXZ_TEAM_PROFILE_CREATE'){
                    formData[item.dict_code] = item.dict_number
                } 
                if(item.dict_code == 'ZXZ_TEAM_PROFILE_CREATE_CONSUME'){
                    formData[item.dict_code] = item.dict_number
                }
                if(item.dict_code == 'ZXZ_TEAM_PROFILE_AUTH_PEOPLE'){
                    formData[item.dict_code] = item.dict_number == 1?true:false
                } 
                if(item.dict_code == 'ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME'){
                    formData[item.dict_code] = item.dict_number == 1?true:false
                    formData['ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME_number'] = item.dict_value
                     profileData['ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME_number'] = item.Id
                }
            })
            page.total = res.data.length - 2;
        }
    })
}



const exportBatchLoading = ref(false);
const exportAllLoading = ref(false);
const exportProjectAnalysisFun = (type: Number) => {
  let ids = checkAll.value?[]:selectData.value
  exportAllLoading.value = true
  incomeExport({ids}).then((res: any) => {
    exportAllLoading.value = false
    if (res.code === 200 && res.data) {
      window.open(res.data)
      ElMessage.success("导出成功！")
    } else {
      ElMessage.success("导出失败！")
    }
  })
}


getProfile()
</script>

<style scoped lang="scss">
    .layout-container{
    }
    .flex-start-nowrap{
        display: flex;
        justify-content: flex-start;
        flex-wrap: nowrap;
        align-items: center;
    }
    .table{
        margin-top: 20px;
    }
    .layout-container-opts {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 10px;
        margin-top: 10px;
    }
    .layout-container-detail {
    text-align: left;
    background: #ffffff;
    padding: 20px;
    box-sizing: border-box;}
    
</style>